package com.example.ajshu.common.utils;
import java.security.GeneralSecurityException;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;

import com.sun.mail.util.MailSSLSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;


public class EmailUtils {

    private static final Logger logger = LoggerFactory.getLogger(EmailUtils.class);

    public static boolean sendHtmlMail(String subject,String content,String receiver){

        boolean result = true;

        try{
            JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();

            // 设定mail server
            senderImpl.setHost("smtp.qq.com");
            senderImpl.setPort(465);
            senderImpl.setUsername("459162765@qq.com");     // 根据自己的情况,设置发件邮箱地址
            senderImpl.setPassword("xfxjwfasevrcbgda"); //ytrnfsyomsdcgbgh     // 根据自己的情况, 设置password
            senderImpl.setDefaultEncoding("UTF-8");
            Properties prop = new Properties();
           // Session session= Session.getDefaultInstance(prop);

            try {
                MailSSLSocketFactory sf = new MailSSLSocketFactory();
                sf.setTrustAllHosts(true);
                prop.put("mail.smtp.ssl.socketFactory",sf);
            } catch (GeneralSecurityException e) {
                e.printStackTrace();
            }
            prop.put("mail.smtp.auth", "true");           // 将这个参数设为true，让服务器进行认证,认证用户名和密码是否正确
            prop.put("mail.smtp.ssl.enable", "true");

            senderImpl.setJavaMailProperties(prop);

            // 建立邮件消息,发送简单邮件和html邮件的区别
            MimeMessage mailMessage = senderImpl.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage);

            // 设置收件人，寄件人
            messageHelper.setTo(receiver);
            messageHelper.setFrom("459162765@qq.com");
            messageHelper.setSubject(subject);
            // true 表示启动HTML格式的邮件
            messageHelper.setText(content,true);

            // 发送邮件
            senderImpl.send(mailMessage);
        } catch (MessagingException e) {
            result = false;
            logger.info("EmailUtils.method [sendHtmlMail]: email send result-" + result +",error message-" + e);
        }

        return result;
    }

}